#!/usr/bin/env python3
# -*- coding:utf-8 -*-

"""
功 能：查询某个城市/国家的当前时间
版权信息：华为技术有限公司，版本所有(C) 2019-2029
"""

import requests
import json

type_dict = {"五言绝句": 0, "七言绝句": 1, "五言律诗": 2, "七言律诗": 3}
def handler(event, context):
    token_response = requests.post("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens",
        headers={"Content-Type": "application/json"}, 
        json={"auth": {
            "identity": {"password": {"user": {"domain": {"name": "账号名"},
                                               "name": "用户名",
                                               "password": "密码"}},
                         "methods": ["password"]},
            "scope": {"project": {"name": "cn-north-4"}}}})
    token = token_response.headers.get("X-Subject-Token")
    project_id = json.loads(token_response.content).get("token").get("project").get("id")
    slot_temp = json.dumps(event, ensure_ascii=False)
    slot_info = json.loads(slot_temp)
    poem_name = slot_info["slots"]["poetryName"][0]
    poetry_type = slot_info["slots"]["poetryType"][0]
    poem_type = type_dict[poetry_type]
    poem_acrostic = slot_info["slots"]["acrostic"][0]
    if (poem_acrostic == "true"):
        poem_acrostic = True
    else :
        poem_acrostic = False
    base_uri = "https://nlp-ext.cn-north-4.myhuaweicloud.com/v1/{}/nlg/poem"
    response = requests.post(base_uri.format(project_id),
        headers={"X-Auth-Token": token, "Content-Type": "application/json"},
        json={"type": poem_type, "title": poem_name, "acrostic": poem_acrostic})
    if response.status_code == 200:
        poem = json.loads(response.text.encode("utf-8"))["poem"]
        return "\n".join(poem)
    else:
        return response.text